﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ThridGroup.ERP.DTO.ProductionSystem;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Microsoft.Extensions.Logging;

namespace ThridGroup.ERP.ProductionSystem
{
    /// <summary>
    /// 设备台账服务实现
    /// </summary>
    public class DeviceLedgerServices : ApplicationService, IDeviceLedgerServices
    {
        private readonly IRepository<DeviceLedgerModel, int> _peviceLedgerRepository;
        private readonly IRepository<EquipmentTypeModel, int> _equipmentTypeModelRepository;
        private readonly ILogger<DeviceLedgerServices> _logger;

        /// <summary>
        /// 设备台账服务构造函数
        /// </summary>
        /// <param name="peviceLedgerRepository">设备台账仓储</param>
        /// <param name="equipmentTypeModelRepository">设备分类</param>
        /// <param name="logger">日志</param>
        public DeviceLedgerServices(IRepository<DeviceLedgerModel, int> peviceLedgerRepository, IRepository<EquipmentTypeModel, int> equipmentTypeModelRepository, ILogger<DeviceLedgerServices> logger)
        {
            _peviceLedgerRepository = peviceLedgerRepository;
            _equipmentTypeModelRepository = equipmentTypeModelRepository;
            _logger = logger;
        }
       /// <summary>
       /// 提交设备台账
       /// </summary>
       /// <param name="createDeviceLedgerDto"></param>
       /// <returns></returns>
       /// <exception cref="NotImplementedException"></exception>
        public async Task<int> AddDeviceLedger(CreateDeviceLedgerDto createDeviceLedgerDto)
        {
           var result= ObjectMapper.Map<CreateDeviceLedgerDto, DeviceLedgerModel>(createDeviceLedgerDto);
            await _peviceLedgerRepository.InsertAsync(result);
            return result.Id;
        }

        /// <summary>
        /// 删除设备台账
        /// </summary>
        /// <param name="id">设备台账ID</param>
        /// <returns></returns>
        public async Task DeleteDeviceLedger(int id)
        {
            await _peviceLedgerRepository.DeleteAsync(id);
        }

        /// <summary>
        /// 获取设备类型列表
        /// </summary>
        /// <returns>设备类型列表</returns>
        public async Task<List<EquipmentTypeListDto>> GetEquipmentTypeListAsync()
        {
            try
            {
                // 获取所有设备类型
                var items = await _equipmentTypeModelRepository.GetListAsync();

                // 转换为DTO
                var dtos = ObjectMapper.Map<List<EquipmentTypeModel>, List<EquipmentTypeListDto>>(items);

                return dtos;
            }
            catch (Exception ex)
            {
                throw new Exception($"获取设备类型列表失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取设备分类树
        /// </summary>
        /// <returns></returns>
        public async Task<List<EquipmentTypeTreeDto>> GetEquipmentTypeTreeAsync()
        {
            // 获取所有设备类型
            var allTypes = await _equipmentTypeModelRepository.GetListAsync();
            
            // 构建树形结构
            var treeList = new List<EquipmentTypeTreeDto>();
            
            // 将所有类型转换为DTO
            foreach (var type in allTypes)
            {
                var dto = new EquipmentTypeTreeDto
                {
                    Id = type.Id,
                    EquipmentTypeName = type.EquipmentTypeName,
                    EquipmentTypeCode= type.EquipmentTypeCode,
                    IsEnable = type.IsEnable,
                    Notes = type.Notes,
                  
                };
                treeList.Add(dto);
            }

            return treeList;
        }

        /// <summary>
        /// 获取设备台账列表（分页、联表查询）
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="limit">每页数量</param>
        /// <param name="deviceCode">设备编码（模糊查询）</param>
        /// <param name="deviceName">设备名称（模糊查询）</param>
        /// <param name="equipmentTypeCode">设备分类编码</param>
        /// <returns>分页后的设备台账列表</returns>
        public async Task<PagedResultDto<DeviceLedgerDtoList>> GetDeviceLedgerList(int page, int limit, string deviceCode = null, string deviceName = null, string equipmentTypeCode = null)
        {
            try
            {
                // 创建查询
                var query = from device in await _peviceLedgerRepository.GetQueryableAsync()
                           join equipType in await _equipmentTypeModelRepository.GetQueryableAsync()
                           on device.EquipmentTypeCode equals equipType.EquipmentTypeCode
                           select new { Device = device, EquipmentType = equipType };

                // 应用筛选条件
                if (!string.IsNullOrWhiteSpace(deviceCode))
                {
                    query = query.Where(x => x.Device.DeviceCode.Contains(deviceCode));
                }

                if (!string.IsNullOrWhiteSpace(deviceName))
                {
                    query = query.Where(x => x.Device.DeviceName.Contains(deviceName));
                }
                
                if (!string.IsNullOrWhiteSpace(equipmentTypeCode))
                {
                    // 确保这里使用的是设备类型编码字段
                    query = query.Where(x => x.Device.EquipmentTypeCode == equipmentTypeCode);
                    _logger.LogInformation($"按设备类型筛选: {equipmentTypeCode}");
                }

                // 获取总记录数
                var totalCount = await AsyncExecuter.CountAsync(query);
                
                // 打印筛选后的记录数
                _logger.LogInformation($"筛选后的记录数: {totalCount}, 筛选条件: 设备编码={deviceCode}, 设备名称={deviceName}, 设备类型={equipmentTypeCode}");

                // 获取分页数据
                var items = await AsyncExecuter.ToListAsync(
                    query.OrderByDescending(x => x.Device.Id)
                         .Skip((page - 1) * limit)
                         .Take(limit)
                );

                // 转换为DTO
                var dtos = items.Select(x => new DeviceLedgerDtoList
                {
                    Id = x.Device.Id,
                    DeviceCode = x.Device.DeviceCode,
                    DeviceName = x.Device.DeviceName,
                    Brand = x.Device.Brand,
                    Specification = x.Device.Specification,
                    Workshop = x.Device.Workshop,
                    Note = x.Device.Note,
                    EquipmentTypeCode = x.EquipmentType.EquipmentTypeCode,
                    EquipmentTypeName = x.EquipmentType.EquipmentTypeName
                }).ToList();

                // 返回分页结果
                return new PagedResultDto<DeviceLedgerDtoList>(totalCount, dtos);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取设备台账列表失败: {ex.Message}");
                throw new Exception($"获取设备台账列表失败: {ex.Message}");
            }
        }

        public async Task<int> UpdateDeviceLedger(CreateDeviceLedgerDto createDeviceLedgerDto)
        {
            if (createDeviceLedgerDto.Id <= 0)
            {
                throw new ArgumentException("设备台账ID无效");
            }

            var entity = await _peviceLedgerRepository.FindAsync(createDeviceLedgerDto.Id);
            if (entity == null)
            {
                throw new ArgumentException($"未找到ID为{createDeviceLedgerDto.Id}的设备台账");
            }

            ObjectMapper.Map(createDeviceLedgerDto, entity);
            await _peviceLedgerRepository.UpdateAsync(entity);
            return entity.Id;
        }

        /// <summary>
        /// 根据ID获取单条设备台账信息（用于编辑反填）
        /// </summary>
        /// <param name="id">设备台账ID</param>
        /// <returns>设备台账详情</returns>
        public async Task<DeviceLedgerDtoList> GetDeviceLedgerById(int id)
        {
            // 查询设备台账实体
            var entity = await _peviceLedgerRepository.GetAsync(id);
            if (entity == null)
            {
                throw new ArgumentException($"未找到ID为{id}的设备台账");
            }

            // 查询设备类型信息
            var equipmentType = await _equipmentTypeModelRepository.FirstOrDefaultAsync(x => x.EquipmentTypeCode == entity.EquipmentTypeCode);

            // 映射为DTO
            var dto = ObjectMapper.Map<DeviceLedgerModel, DeviceLedgerDtoList>(entity);
            if (equipmentType != null)
            {
                dto.EquipmentTypeCode = equipmentType.EquipmentTypeCode;
                dto.EquipmentTypeName = equipmentType.EquipmentTypeName;
            }

            return dto;
        }

        public async Task BatchDeleteDeviceLedger(int[] ids)
        {
            await _peviceLedgerRepository.DeleteManyAsync(ids);
        }
    }

       
}
